package com.zhang.third.day03;

import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

/**
 * @title: 自定义物理分区
 * @author: zhang
 * @date: 2022/4/6 09:50
 */
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .fromElements(1, 2, 3, 4, 5, 6, 7, 8)
                .partitionCustom(
                        // 根据数据key发送到指定的并行子任务
                        // numPartitions是下游算子的并行度
                        new Partitioner<Integer>() {
                            @Override
                            public int partition(Integer key, int numPartitions) {
                                return key % numPartitions;
                            }
                        },
                        // 为每个数据指定分区key
                        new KeySelector<Integer, Integer>() {
                            @Override
                            public Integer getKey(Integer value) throws Exception {
                                //return value % 2;
                                //value: 1,2,3,4,5,6,7,8
                                //  key: 1,0,1,0,1,0,1,0
                                return value;
                            }
                        }
                )
                .print().setParallelism(3);

        env.execute();
    }
}
